import BaseOAuthProvider from "./base-provider";
import type { OAuthConfig } from "./base-provider";
import axios from 'axios';
import { OAuthUserInfo } from "@/service/oauthService";


class GoogleProvider extends BaseOAuthProvider {
    authUrl: string;
    tokenUrl: string;
    userInfoUrl: string;

    constructor(config: OAuthConfig) {
        super(config);
        this.authUrl = 'https://accounts.google.com/o/oauth2/v2/auth';
        this.tokenUrl = 'https://oauth2.googleapis.com/token';
        this.userInfoUrl = 'https://www.googleapis.com/oauth2/v2/userinfo';

    }

    async exchangeCodeForTokens(code: string) {
        try {
            // Google OAuth需要使用application/x-www-form-urlencoded格式
            const params = new URLSearchParams({
                client_id: this.clientId,
                client_secret: this.clientSecret,
                code: code,
                grant_type: 'authorization_code',
                redirect_uri: this.redirectUri
            });

            const response = await axios.post(this.tokenUrl, params.toString(), {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                timeout: 10000 // 10秒超时
            });

            // 验证响应数据
            if (!response.data.access_token) {
                throw new Error('No access token received from Google');
            }

            return response.data;
        } catch (error: any) {
            if (error.response) {
                // Google API返回的错误
                const errorData = error.response.data;
                const errorMessage = errorData.error_description || errorData.error || error.message;
                throw new Error(`Google token exchange failed: ${errorMessage} (HTTP ${error.response.status})`);
            } else if (error.request) {
                // 网络错误
                throw new Error(`Google token exchange failed: Network error - ${error.message}`);
            } else {
                // 其他错误
                throw new Error(`Google token exchange failed: ${error.message}`);
            }
        }
    }

    async getUserInfo(accessToken: string) {
        try {
            const response = await axios.get(this.userInfoUrl, {
                headers: {
                    'Authorization': `Bearer ${accessToken}`
                },
                timeout: 10000 // 10秒超时
            });

            // 验证响应数据
            if (!response.data.id || !response.data.email) {
                throw new Error('Invalid user info received from Google');
            }

            return response.data;
        } catch (error: any) {
            if (error.response) {
                // Google API返回的错误
                const status = error.response.status;
                if (status === 401) {
                    throw new Error('Google user info fetch failed: Invalid or expired access token');
                } else {
                    throw new Error(`Google user info fetch failed: HTTP ${status}`);
                }
            } else if (error.request) {
                // 网络错误
                throw new Error('Google user info fetch failed: Network error');
            } else {
                // 其他错误
                throw new Error(`Google user info fetch failed: ${error.message}`);
            }
        }
    }

    processUserData(userInfo: any): OAuthUserInfo {
        // 处理用户姓名的逻辑
        let name = userInfo.nickname;
        if (!name && userInfo.name) {
            name = userInfo.name;
        } else if (!name && userInfo.given_name && userInfo.family_name) {
            name = `${userInfo.given_name} ${userInfo.family_name}`;
        } else if (!name && userInfo.given_name) {
            name = userInfo.given_name;
        } else if (!name && userInfo.family_name) {
            name = userInfo.family_name;
        } else if (!name && userInfo.email) {
            name = userInfo.email.split('@')[0];
        } else if (!name) {
            name = 'Google User';
        }

        return {
            id: userInfo.sub.toString(), // 确保ID是字符串
            email: userInfo.email,
            name: name,
            avatar: userInfo.picture || undefined
        };
    }
}

export default GoogleProvider;